package com.fingard.dsp.bank.directbank.icbc02;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.icbc02.util.*;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.icbc.api.DefaultIcbcClient;

import java.util.Date;

/**
 * 参考文档：中国工商银行代理保险保费代扣及协议管理API接口规范
 */
public class ICBC02Contract extends ICBC02Base implements IContract {
    /**
     * 开发接口:中国工商银行代理保险客户保费代扣协议签订
     * 中国工商银行代理保险客户保费代扣协议确认
     */
    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.contractDetail.recAct, "contract");
            if (actItem == null) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req.contractDetail.recAct + "]商户配置信息";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String aesKey = getBankConfig().getValueAsString("aesKey");
            String privateKey = FileHelper.readFileText(actItem.ownKeyStorePath, getCharset());
            String publicKey = FileHelper.readFileText(actItem.oppCertFilePath, getCharset());
            DefaultIcbcClient client = new DefaultIcbcClient(actItem.appId, "RSA2", privateKey, "UTF-8", "json", publicKey, "AES", aesKey, (String) null, (String) null);
            if ("01".equals(p_req.contractDetail.step)) {
                // 请求实体
                MybankPayInsuranceCustprtlCustprtlsignRequestV1 request = new MybankPayInsuranceCustprtlCustprtlsignRequestV1();
                // bizContent实体
                MybankPayInsuranceCustprtlCustprtlsignRequestV1.CustPrtlSignRequestV1Biz bizContent
                        = new MybankPayInsuranceCustprtlCustprtlsignRequestV1.CustPrtlSignRequestV1Biz();
                MybankPayInsuranceCustprtlCustprtlsignRequestV1.CommonReqInfo commonReqInfoContent
                        = new MybankPayInsuranceCustprtlCustprtlsignRequestV1.CommonReqInfo();
                MybankPayInsuranceCustprtlCustprtlsignRequestV1.TransReqInfo transReqInfoContent
                        = new MybankPayInsuranceCustprtlCustprtlsignRequestV1.TransReqInfo();
                MybankPayInsuranceCustprtlCustprtlsignRequestV1.BizContentInfo bizContentInfo =
                        new MybankPayInsuranceCustprtlCustprtlsignRequestV1.BizContentInfo();

                commonReqInfoContent.setChanNo("15");
                commonReqInfoContent.setInsuId(bankFront.corpNo);
                commonReqInfoContent.setTransDate(Format.Date10Format.format(new Date()));
                commonReqInfoContent.setTransTime(Format.Time8Format.format(new Date()));
                commonReqInfoContent.setZoneNo(actItem.areaCode);
                commonReqInfoContent.setBrNo(actItem.cnapsCode);

                transReqInfoContent.setCustAccno(p_req.contractDetail.payAct);
                transReqInfoContent.setCustName(p_req.contractDetail.payName);
                transReqInfoContent.setCustIdNo(p_req.contractDetail.certNum);
                transReqInfoContent.setCustIdType(convertCertTypeToBank(p_req.contractDetail.certType));
                transReqInfoContent.setInsuPrtlNo(p_req.contractDetail.insuPolicyNum);
                transReqInfoContent.setCustMobile(p_req.contractDetail.cellPhone);
                transReqInfoContent.setCustPayFreq("1");
                //单笔扣款限额
                String singleLimit = p_req.contractDetail.singleLimit;
                if (StringHelper.isNullOrEmpty(singleLimit)) {
                    singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
                }
                transReqInfoContent.setLmtAmt(StringHelper.amountMultiply100(singleLimit));
                transReqInfoContent.setInsuPrtlType("1");
                transReqInfoContent.setPrtlBeginDate(Format.Date10Format.format(new Date()));
                //协议到期日期
                String deadLine = p_req.contractDetail.deadLine;
                if (StringHelper.isNullOrEmpty(deadLine)) {
                    deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
                }
                transReqInfoContent.setPrtlEndDate(Format.Date10Format.format(Format.Date8Format.parse(deadLine)));
                transReqInfoContent.setPrtlNote(p_req.contractDetail.memo);
                transReqInfoContent.setSignChan("1");

                bizContentInfo.setCommonReqInfo(commonReqInfoContent);
                bizContentInfo.setTransReqInfo(transReqInfoContent);
                bizContent.setBizContentInfo(bizContentInfo);
                request.setServiceUrl(bankFront.getUrl("contract"));
                request.setBizContent(bizContent);

                WriteBankLogStep2(JSONObject.toJSONString(request));
                MybankPayInsuranceCustprtlCustprtlsignResponseV1 response = client.execute(request, p_req.reqHeader.transSeqID);
                WriteBankLogStep3(JSONObject.toJSONString(response));

                if ("0".equals(response.getRetCode())) {
                    // 业务成功处理
                    String respCode = response.getRetCode();
                    String tmpRespInfo = response.getReturnMsg();
                    String status = response.getRespContent().getTransRepInfo().getPrtlStatus();
                    if (respCode != null && "0".equals(respCode)) {
                        tmpRetDetail.signConfirmType = "2";
                        tmpRetDetail.authCode = response.getRespContent().getTransRepInfo().getPrtlNo();
                        tmpRetDetail.token = response.getRespContent().getTransRepInfo().getSmCfmSeq();
                        if ("1".equals(status)) {
                            tmpRetDetail.signState = ContractState.SUCCESS;
                        } else if ("2".equals(status)) {
                            tmpRetDetail.signState = ContractState.SIGNING;
                        } else if ("3".equals(status)) {
                            tmpRetDetail.signState = ContractState.FAIL;
                        }
                    }
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpRespInfo;
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", respCode);
                } else {
                    // 失败
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = response.getReturnMsg();
                    tmpRetDetail.signState = PaymentState.FAIL;
                }
            } else if ("02".equals(p_req.contractDetail.step)) {
                MybankPayInsuranceCustprtlCustprtlconfirmRequestV1 request = new MybankPayInsuranceCustprtlCustprtlconfirmRequestV1();
                // bizContent实体
                MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.CustprtlConfirmRequestV1Biz bizContent
                        = new MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.CustprtlConfirmRequestV1Biz();
                MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.CommonReqInfo commonReqInfoContent
                        = new MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.CommonReqInfo();
                MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.TransReqInfo transReqInfoContent
                        = new MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.TransReqInfo();
                MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.BizContentInfo bizContentInfo =
                        new MybankPayInsuranceCustprtlCustprtlconfirmRequestV1.BizContentInfo();

                commonReqInfoContent.setChanNo("15");
                commonReqInfoContent.setInsuId(bankFront.corpNo);
                commonReqInfoContent.setTransDate(Format.Date10Format.format(new Date()));
                commonReqInfoContent.setTransTime(Format.Time8Format.format(new Date()));
                commonReqInfoContent.setZoneNo(actItem.areaCode);
                commonReqInfoContent.setBrNo(actItem.cnapsCode);

                transReqInfoContent.setCustName(p_req.contractDetail.payName);
                transReqInfoContent.setCustIdNo(p_req.contractDetail.certNum);
                transReqInfoContent.setCustIdType(convertCertTypeToBank(p_req.contractDetail.certType));
                transReqInfoContent.setPrtlNo(p_req.contractDetail.authCode);
                transReqInfoContent.setSmCfmCode(p_req.contractDetail.smsCode);//短信验证码
                bizContentInfo.setCommonReqInfo(commonReqInfoContent);
                bizContentInfo.setTransReqInfo(transReqInfoContent);
                bizContent.setBizContentInfo(bizContentInfo);
                request.setServiceUrl(bankFront.getUrl("contractConfirm"));
                request.setBizContent(bizContent);

                WriteBankLogStep2(JSONObject.toJSONString(bizContent));
                MybankPayInsuranceCustprtlCustprtlconfirmResponseV1 response = client.execute(request, p_req.reqHeader.transSeqID);
                WriteBankLogStep3(JSONObject.toJSONString(response));

                if ("0".equals(response.getRetCode())) {
                    String respCode = response.getRetCode();
                    String tmpRespInfo = response.getReturnMsg();
                    String status = response.getRespContent().getTransRepInfo().getPrtlStatus();
                    if (respCode != null && "0".equals(respCode)) {
                        tmpRetDetail.signConfirmType = "2";
                        if ("1".equals(status)) {
                            tmpRetDetail.signState = ContractState.SUCCESS;
                        } else if ("2".equals(status)) {
                            tmpRetDetail.signState = ContractState.SIGNING;
                        } else if ("3".equals(status)) {
                            tmpRetDetail.signState = ContractState.FAIL;
                        }
                    }
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpRespInfo;
                    tmpRetDetail.authCode = response.getRespContent().getTransRepInfo().getPrtlNo();
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", respCode);
                } else {
                    // 失败
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = response.getReturnMsg();
                    tmpRetDetail.signState = PaymentState.FAIL;
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    /**
     * 开发接口:中国工商银行代理保险客户保费代扣协议查询
     */
    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQry.contractDetail.recAct, "contract");
            if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
                tmpRetDetail.respCode = "0";
                if (actItem == null) {
                    tmpRetDetail.respInfo = "未找到账号" + p_reqQry.contractDetail.recAct + "的批量商户配置节点";
                } else {
                    tmpRetDetail.respInfo = "账号" + p_reqQry.contractDetail.recAct + "的证书文件不存在";
                }
                tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String aesKey = getBankConfig().getValueAsString("aesKey");
            String privateKey = FileHelper.readFileText(actItem.ownKeyStorePath, getCharset());
            String publicKey = FileHelper.readFileText(actItem.oppCertFilePath, getCharset());
            DefaultIcbcClient client = new DefaultIcbcClient(actItem.appId, "RSA2", privateKey, "UTF-8", "json", publicKey, "AES", aesKey, (String) null, (String) null);

            MybankPayInsuranceCustprtlCustprtlqryRequestV1 request = new MybankPayInsuranceCustprtlCustprtlqryRequestV1();
            // bizContent实体
            MybankPayInsuranceCustprtlCustprtlqryRequestV1.CustPrtlInfoRequestV1Biz bizContent
                    = new MybankPayInsuranceCustprtlCustprtlqryRequestV1.CustPrtlInfoRequestV1Biz();
            MybankPayInsuranceCustprtlCustprtlqryRequestV1.CommonReqInfo commonReqInfoContent
                    = new MybankPayInsuranceCustprtlCustprtlqryRequestV1.CommonReqInfo();
            MybankPayInsuranceCustprtlCustprtlqryRequestV1.TransReqInfo transReqInfoContent
                    = new MybankPayInsuranceCustprtlCustprtlqryRequestV1.TransReqInfo();
            MybankPayInsuranceCustprtlCustprtlqryRequestV1.BizContentInfo bizContentInfo =
                    new MybankPayInsuranceCustprtlCustprtlqryRequestV1.BizContentInfo();
            commonReqInfoContent.setChanNo("15");
            commonReqInfoContent.setInsuId(bankFront.corpNo);
            commonReqInfoContent.setTransDate(Format.Date10Format.format(new Date()));
            commonReqInfoContent.setTransTime(Format.Time8Format.format(new Date()));
            commonReqInfoContent.setZoneNo(actItem.areaCode);
            commonReqInfoContent.setBrNo(actItem.cnapsCode);


            transReqInfoContent.setCustIdNo(p_reqQry.contractDetail.payName);//客户姓名
            transReqInfoContent.setCustIdType(convertCertTypeToBank(p_reqQry.contractDetail.certType));//客户证件类型CODE1
            transReqInfoContent.setCustName(p_reqQry.contractDetail.certNum);//客户证件号码
            if (StringHelper.isNullOrEmpty(p_reqQry.contractDetail.authCode)) {
                tmpRetDetail.signState = ContractState.UNSIGNED;
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "记录不存在";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            transReqInfoContent.setPrtlNo(p_reqQry.contractDetail.authCode);//协议编号

            bizContentInfo.setCommonReqInfo(commonReqInfoContent);
            bizContentInfo.setTransReqInfo(transReqInfoContent);

            bizContent.setBizContentInfo(bizContentInfo);
            request.setServiceUrl(bankFront.getUrl("queryContract"));
            request.setBizContent(bizContent);

            WriteBankLogStep2(JSONObject.toJSONString(bizContent));
            MybankPayInsuranceCustprtlCustprtlqryResponseV1 response = client.execute(request, p_reqQry.reqHeader.transSeqID);
            WriteBankLogStep3(JSONObject.toJSONString(response));

            if ("0".equals(response.getRetCode())) {
                String respCode = response.getRetCode();
                String tmpRespInfo = response.getReturnMsg();
                String status = response.getRespContent().getTransRepInfo().getPrtlStatus();
                if (respCode != null && "0".equals(respCode)) {
                    tmpRetDetail.signConfirmType = "2";
                    if ("1".equals(status)) {
                        tmpRetDetail.signState = ContractState.SUCCESS;
                    } else if ("2".equals(status)) {
                        tmpRetDetail.signState = ContractState.SIGNING;
                    } else if ("3".equals(status)) {
                        tmpRetDetail.signState = ContractState.FAIL;
                    }
                    tmpRetDetail.authCode = response.getRespContent().getTransRepInfo().getPrtlNo();
                    tmpRetDetail.payAct = response.getRespContent().getTransRepInfo().getCustAccno();
                    tmpRetDetail.payName = response.getRespContent().getTransRepInfo().getCustName();
                    tmpRetDetail.cellPhone = response.getRespContent().getTransRepInfo().getCustMobile();
                    tmpRetDetail.certType = response.getRespContent().getTransRepInfo().getCustIdType();
                    tmpRetDetail.certNum = response.getRespContent().getTransRepInfo().getCustIdNo();
                    tmpRetDetail.deadLine = response.getRespContent().getTransRepInfo().getPrtlEndDate();
                }
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpRespInfo;
                tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", respCode);
            } else {
                // 失败
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = response.getReturnMsg();
                tmpRetDetail.signState = PaymentState.FAIL;
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
